package com.oocl.aeat.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.aeat.dto.JsonResult;
import com.oocl.aeat.service.SysUserService;
import com.oocl.aeat.service.factory.SysUserServiceFactory;
import com.oocl.aeat.util.Const;
import com.oocl.aeat.util.JsonUtil;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SysUserService sysUserService;
    public LoginServlet() {
    	sysUserService = SysUserServiceFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("login.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		if("".equals(name)||"".equals(pwd)){
			JsonResult result = new JsonResult(Const.JSON_FAIL,"Username or password cannot empty.",null);
			out.write(JsonUtil.getJsonFromObject(result));
			out.flush();
			return;
		}
		
		if(sysUserService.login(name, pwd)){
			request.getSession().setAttribute("sysuser", name);
			JsonResult result = new JsonResult(Const.JSON_SUCCESS,"success",null);
			out.write(JsonUtil.getJsonFromObject(result));
			out.flush();
			return;
		}else{
			JsonResult result = new JsonResult(Const.JSON_FAIL,"Username or Password wrong.",null);
			out.write(JsonUtil.getJsonFromObject(result));
			out.flush();
			return;
		}
	}

}
